package com.baizhi.cmfzdemo.util;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2019/4/15.
 */
public class LuceneUtil {
    /**
     * 创建分词器
     */
    private static StandardAnalyzer analyzer;
    /**
     * 指明索引库的位置
     */
    private static FSDirectory directory;


    static {
        try {
            analyzer = new StandardAnalyzer(Version.LUCENE_44);
            directory = FSDirectory.open(new File("E://LuceneTest"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取索引写出对象
     * @return
     */
    public static IndexWriter getIndexWriter(){
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_44, analyzer);
        IndexWriter indexWriter = null;
        try {
            indexWriter = new IndexWriter(directory, indexWriterConfig);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return indexWriter;
    }

    /**
     * 处理关键词
     * @param keyword
     * @return
     */
    public static Query getQuery(String keyword){
        StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);
        String[] field = {"articleId","articleName","articleImage","articleContent"};
        MultiFieldQueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_44,field,analyzer);
        Query query = null;
        try {
            query = queryParser.parse(keyword);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return query;
    }

    /**
     * 获取查询对象
     * @return
     */
    public static IndexSearcher getIndexSearcher(){
        DirectoryReader reader = null;
        try {
            reader = DirectoryReader.open(directory);
        } catch (IOException e) {
            System.out.println("索引库不能为空");
        }
//        4.使用读取到的索引 进行查询
        IndexSearcher indexSearcher = new IndexSearcher(reader);
        return indexSearcher;
    }

    /**
     * 提交方法
     * @param indexWriter
     */
    public static void commit(IndexWriter indexWriter){
        try {
            indexWriter.commit();
            indexWriter.close();
        } catch (IOException e) {
            try {
                indexWriter.rollback();
                indexWriter.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }


}
